⚠️ Advertencia crítica antes de correr cualquier script
No ejecutes este tipo de script en un ambiente de producción, carpeta real, servidor compartido, unidad de red o sistema institucional sin autorización formal.
PowerShell es una herramienta poderosa: un comando de renombrado masivo puede modificar cientos o miles de archivos en segundos. En una carpeta equivocada, eso puede causar pérdida de trazabilidad, fallos en procesos automáticos, interrupciones operativas o incidentes de ciberseguridad.
Regla obligatoria del training: primero se trabaja con data sintética, luego se valida con una muestra pequeña, después se prueba con -WhatIf cuando aplique, y solo entonces se considera ejecutar en datos reales siguiendo los protocolos de la organización.
- Permisos: usa solamente carpetas donde tengas autorización explícita.
- Backups: confirma que exista copia de seguridad o posibilidad real de recuperación.
- Cybersecurity: cumple las políticas internas, controles de acceso, change management y principios de menor privilegio.
- Producción: nunca ejecutes scripts masivos directamente sobre producción sin revisión, aprobación y plan de reversa.
⚠️ Critical warning before running any script
Do not run this type of script in a production environment, real folder, shared server, network drive, or institutional system without formal authorization.
PowerShell is a powerful tool: a bulk command can modify hundreds or thousands of files in seconds. In the wrong folder, it can break traceability, disrupt automated processes, create operational issues, or trigger cybersecurity incidents.
Mandatory training rule: start with synthetic data, validate with a small sample, test with -WhatIf when applicable, and only then consider real data while following your organization’s protocols.
- Permissions: use only folders where you have explicit authorization.
- Backups: confirm that a backup or real recovery option exists.
- Cybersecurity: follow internal policies, access controls, change management, and least-privilege principles.
- Production: never run bulk scripts directly on production without review, approval, and rollback planning.
Objetivo del Topic 2
El objetivo es tomar nombres de archivos que contienen letras y números mezclados, y extraer solamente el número que funciona como ID limpio.
Topic 2 Objective
The goal is to take file names that contain mixed letters and numbers, and extract only the number that works as a clean ID.
Ruta de trabajo
Usaremos una carpeta controlada para este ejercicio:
Working folder
We will use a controlled folder for this exercise:
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 2"
Qué vamos a aprender
- Crear nombres de archivos con IDs mezclados.
- Usar BaseName para leer el nombre sin extensión.
- Usar una expresión regular para quitar todo lo que no sea número.
- Generar una tabla de verificación con el nombre original y el ID extraído.
What you will learn
- Create file names with mixed IDs.
- Use BaseName to read the file name without extension.
- Use a regular expression to remove everything that is not a number.
- Generate a verification table with the original name and the extracted ID.
Script 1 — Crear data sintética
Este script crea archivos de práctica con nombres mezclados: letras, espacios, guiones, símbolos y números.
Script 1 — Create synthetic data
This script creates practice files with mixed names: letters, spaces, hyphens, symbols, and numbers.
# ======================================================
# Topic 2 - Script 1
# Create synthetic files with mixed IDs
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 2"
New-Item -Path $BasePath -ItemType Directory -Force | Out-Null
$Files = @(
"EMP-1001 John Smith.jpg",
"Photo_1002_Maria Garcia.jpg",
"ID 1003 - Carlos.jpg",
"P-1004-Badge.jpg",
"Scan Employee 1005.jpg",
"Profile_1006_final.jpg",
"HR-Record-1007.jpg",
"Temp 1008 upload.jpg",
"BadgeNumber_1009.jpg",
"Picture 1010.jpg",
"Employee-ID-1011-New.jpg",
"Archive_1012_old.jpg"
)
foreach ($File in $Files) {
New-Item -Path (Join-Path $BasePath $File) -ItemType File -Force | Out-Null
}
Write-Host "Synthetic files created in:" $BasePath
Get-ChildItem $BasePath -Filter "*.jpg" | Select-Object Name
Script 2 — Extraer el número limpio
Este script lee cada archivo JPG, toma el nombre sin extensión y elimina todo lo que no sea número.
Script 2 — Extract the clean number
This script reads each JPG file, takes the name without the extension, and removes everything that is not a number.
# ======================================================
# Topic 2 - Script 2
# Extract numbers from file names
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 2"
Get-ChildItem $BasePath -Filter "*.jpg" | ForEach-Object {
$id = $_.BaseName -replace "\D", ""
[PSCustomObject]@{
Original_File_Name = $_.Name
Extracted_ID = $id
}
}
Script 3 — Verificar resultados
Este script vuelve a calcular los IDs y los muestra en una tabla ordenada.
Script 3 — Verify results
This script calculates the IDs again and displays them in a sorted table.
# ======================================================
# Topic 2 - Script 3
# Verify extracted IDs
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 2"
Get-ChildItem $BasePath -Filter "*.jpg" |
ForEach-Object {
[PSCustomObject]@{
Original_File_Name = $_.Name
Base_Name = $_.BaseName
Extracted_ID = ($_.BaseName -replace "\D", "")
}
} |
Sort-Object Extracted_ID |
Format-Table -AutoSize
Explicación simple del script
- Get-ChildItem busca los archivos dentro de la carpeta.
- -Filter "*.jpg" limita el trabajo a imágenes JPG.
- $_.BaseName toma el nombre sin la extensión.
- -replace "\D", "" elimina letras, espacios, guiones y símbolos.
- [PSCustomObject] crea una tabla limpia para revisar.
Simple script explanation
- Get-ChildItem finds the files inside the folder.
- -Filter "*.jpg" limits the work to JPG images.
- $_.BaseName takes the name without the extension.
- -replace "\D", "" removes letters, spaces, hyphens, and symbols.
- [PSCustomObject] creates a clean table for review.
Ejemplo esperado
| Nombre original | ID extraído |
|---|---|
| EMP-1001 John Smith.jpg | 1001 |
| Photo_1002_Maria Garcia.jpg | 1002 |
| ID 1003 - Carlos.jpg | 1003 |
| P-1004-Badge.jpg | 1004 |
Expected example
| Original name | Extracted ID |
|---|---|
| EMP-1001 John Smith.jpg | 1001 |
| Photo_1002_Maria Garcia.jpg | 1002 |
| ID 1003 - Carlos.jpg | 1003 |
| P-1004-Badge.jpg | 1004 |
Conclusión
Este topic enseña una habilidad base muy útil: separar IDs reales de nombres de archivos desordenados. Todavía no estamos cambiando archivos; estamos aprendiendo a detectar y validar el dato correcto antes de tomar una acción más fuerte.
Conclusion
This topic teaches a very useful base skill: separating real IDs from messy file names. We are not changing files yet; we are learning how to detect and validate the correct data before taking a stronger action.